package com.ch.clinking.activity;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.icu.util.Calendar;
import android.net.Uri;
import android.nfc.Tag;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.ch.clinking.ClinkingApplication;
import com.ch.clinking.R;
import com.ch.clinking.Utils.NetUtils.DoCallBack;
import com.ch.clinking.Utils.NetUtils.OkHttpUtil;
import com.ch.clinking.bean.ImageRequest;
import com.ch.clinking.bean.Merchandise;
import com.ch.clinking.databinding.ActivityAddMerBinding;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.TimeZone;

public class AddMerActivity extends AppCompatActivity {

    private ActivityAddMerBinding binding;
    private static final int PICK_IMAGE_REQUEST = 1;
    private Bitmap selectedImageBitmap;
    private final Handler handler = new Handler();
    private Merchandise merchandise;
    private boolean uploadImg = false;

    private ClinkingApplication app;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_mer);

        // 设置状态栏图标为深色
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        binding = ActivityAddMerBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());


        initData();
        initEvent();


    }

    private void initEvent() {

        binding.addMerImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openGallery();
            }
        });

        binding.addMerCommit.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onClick(View view) {
                String title = binding.addMerTitle.getText().toString();
                String spu = binding.addMerSpuId.getText().toString();
                String skc = binding.addMerSkcId.getText().toString();
                String price = binding.addMerPrice.getText().toString();
                String productNum = binding.addSKCProductNum.getText().toString();
                // 检查EditText中的文本是否为空
                if (title.equals("") || spu.equals("") || skc.equals("") || price.equals("")) {
                    Log.d("tag", title + spu + skc + price);
                    Toast.makeText(AddMerActivity.this, "信息未填写完全", Toast.LENGTH_SHORT).show();
                    return;
                } else if (!uploadImg) {
                    Toast.makeText(AddMerActivity.this, "未选择商品图片", Toast.LENGTH_SHORT).show();
                    return;
                }

                //  查询SKC是否唯一
                HashMap<String, String> merMap = new HashMap<>();
                merMap.put("skc", skc);

                OkHttpUtil.getInstance().doPostForm("/mer/selectBySKC", new DoCallBack() {
                    @Override
                    public void onSuccess(String result) {
                        Log.d("selectBySKC", result);

                        // 使用 Gson 解析 JSON 字符串
                        Gson gson = new Gson();
                        JsonObject data = gson.fromJson(result, JsonObject.class);

                        // 获取msg字段的值
                        String code = data.get("code").getAsString();

//                                remove(getItem(position));
//                                merchandiseList.remove(position);
//                                List<Merchandise> update = new ArrayList<>();
//                                update.addAll(merchandiseList);
//                                update.remove(position);
//                                merchandiseList = update;
//                                notifyDataSetChanged();
                        Log.d("selectBySKC", code);
                        if (code.equals("500")) {
                            Toast.makeText(AddMerActivity.this, "此SKC已存在，添加失败", Toast.LENGTH_SHORT).show();
                        }else {





                            merchandise = new Merchandise();
                            merchandise.setTitle(title);
                            merchandise.setSkcId(skc);
                            merchandise.setSpuId(spu);
                            merchandise.setPrice(Float.parseFloat(price));
                            merchandise.setShopId(app.shopList.get(app.shopPosition).getShopId());

                            // 获取当前时间
                            Calendar calendar = Calendar.getInstance();
                            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
                            String formattedDateTime = formatter.format(calendar.getTime());

                            merchandise.setFirstImage(skc + "_" + formattedDateTime + ".jpg");
                            merchandise.setProductNumber(productNum);
                            // 创建一个 Date 对象表示当前时间
                            Date currentDate = new Date();

                            // 获取默认时区
                            TimeZone defaultTimeZone = TimeZone.getDefault();

                            // 定义日期格式
                            @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                            // 使用默认时区格式化日期
                            dateFormat.setTimeZone(defaultTimeZone);

                            // 使用 format 方法将 Date 转换为字符串
                            String formattedDate = dateFormat.format(currentDate);
                            merchandise.setCreateTime(formattedDate);
                            merchandise.setShopType(app.shopList.get(app.shopPosition).getShopType());
                            if (app.shopList.get(app.shopPosition).getShopType().equals("标码")) {
                                if (binding.checkBoxXXS.isChecked()) {
                                    merchandise.setActivate_XXS(true);
                                }
                                if (binding.checkBoxXS.isChecked()) {
                                    merchandise.setActivate_XS(true);
                                }
                                if (binding.checkBoxS.isChecked()) {
                                    merchandise.setActivate_S(true);
                                }
                                if (binding.checkBoxM.isChecked()) {
                                    merchandise.setActivate_M(true);
                                }
                                if (binding.checkBoxL.isChecked()) {
                                    merchandise.setActivate_L(true);
                                }
                                if (binding.checkBoxXL.isChecked()) {
                                    merchandise.setActivate_XL(true);
                                }
                                if (binding.checkBoxXXL.isChecked()) {
                                    merchandise.setActivate_XXL(true);
                                }
                            } else {
                                if (binding.checkBox0XL.isChecked()) {
                                    merchandise.setActivate_Plus_0XL(true);
                                }
                                if (binding.checkBox1XL.isChecked()) {
                                    merchandise.setActivate_Plus_1XL(true);
                                }
                                if (binding.checkBox2XL.isChecked()) {
                                    merchandise.setActivate_Plus_2XL(true);
                                }
                                if (binding.checkBox3XL.isChecked()) {
                                    merchandise.setActivate_Plus_3XL(true);
                                }
                                if (binding.checkBox4XL.isChecked()) {
                                    merchandise.setActivate_Plus_4XL(true);
                                }
                                if (binding.checkBox5XL.isChecked()) {
                                    merchandise.setActivate_Plus_5XL(true);
                                }
                                if (binding.checkBox6XL.isChecked()) {
                                    merchandise.setActivate_Plus_6XL(true);
                                }
                            }

                            String merString = new Gson().toJson(merchandise);

                            OkHttpUtil.getInstance().doPostJson("/mer/updateMer", new DoCallBack() {
                                @Override
                                public void onSuccess(String result) {

                                    Log.d("skuUpdate", result);

                                }

                                @Override
                                public void onError(Exception e) {
                                    Log.d("skuUpdate", "error");
                                    Toast.makeText(AddMerActivity.this, "网络错误,请稍后再试", Toast.LENGTH_SHORT).show();
                                }
                            }, merString);

                            // Now you can upload the selectedImageBitmap to your server
                            new UploadImageTask().execute();
                        }



                    }

                    @Override
                    public void onError(Exception e) {
                        Toast.makeText(AddMerActivity.this, "网络错误,请稍后再试", Toast.LENGTH_SHORT).show();
                    }
                }, merMap);



            }
        });
    }

    private void initData() {
        app = ClinkingApplication.getInstance();
        if (app.shopList.get(app.shopPosition).getShopType().equals("标码")) {
            binding.addMerNormalSizeContent.setVisibility(View.VISIBLE);
        } else {
            binding.addMerPlusSizeContent.setVisibility(View.VISIBLE);
        }
    }

    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PICK_IMAGE_REQUEST);
//        registerForActivityResult(intent, PICK_IMAGE_REQUEST)
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            Uri selectedImageUri = data.getData();
            try {
                InputStream inputStream = getContentResolver().openInputStream(selectedImageUri);
                selectedImageBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
                binding.addMerImg.setImageBitmap(selectedImageBitmap);
                uploadImg = true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private class UploadImageTask extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... voids) {
            // Convert the Bitmap to a base64-encoded string
            String imageData = bitmapToBase64(selectedImageBitmap);

            // Perform your HTTP request here to upload the image to the server
            // For example, you can use HttpClient or HttpURLConnection

            // Dummy example: Send the base64-encoded image data to a server
            String serverResponse = sendImageToServer(imageData);

            return serverResponse;
        }

        @Override
        protected void onPostExecute(String result) {
            // Handle the server response here
//            Toast.makeText(AddMerActivity.this, "Image uploaded to server", Toast.LENGTH_SHORT).show();
        }
    }

    private String bitmapToBase64(Bitmap bitmap) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        return Base64.encodeToString(byteArray, Base64.DEFAULT);
    }

    private String sendImageToServer(String imageData) {
        ImageRequest imageRequest = new ImageRequest();
        imageRequest.setBase64Image(imageData);
        imageRequest.setName(merchandise.getFirstImage());
        String imageJson = new Gson().toJson(imageRequest);
        OkHttpUtil.getInstance().doPostJson("/mer/uploadImage", new DoCallBack() {
            @Override
            public void onSuccess(String result) {
                Log.d("tag", "UploadImage" + result);
                AddMerActivity.this.finish();
            }

            @Override
            public void onError(Exception e) {
                Toast.makeText(AddMerActivity.this, "网络错误,请稍后再试", Toast.LENGTH_SHORT).show();
                handler.postDelayed(AddMerActivity.this::finish, 2000);
            }
        }, imageJson);
        return "Server response: Image send";
    }
}